/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import model.Hinhanh;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author HoangLiem
 */
public class HinhAnhDAO {

    public static ArrayList<Hinhanh> getImage(String maSanPham) {
        ArrayList<Hinhanh> list = null;
        try {
            SessionFactory ssFac = HibernateUtil.getSessionFactory();
            Session session = ssFac.getCurrentSession();
            session.beginTransaction();
            String hql = "from Hinhanh ha where ha.sanpham.maSanPham=:maSanPham";
            Query query = session.createQuery(hql);
            query.setString("maSanPham", maSanPham);
            list = (ArrayList<Hinhanh>) query.list();
        } catch (Exception ex) {
            ex.printStackTrace();
            list = null;
        }
        return list;
    }

    public static boolean insert(Hinhanh ha) {
        boolean result = false;
        try {
            SessionFactory ssFac = HibernateUtil.getSessionFactory();
            Session session = ssFac.getCurrentSession();
            Transaction trans = session.beginTransaction();
            trans.begin();
            session.merge(ha);
            result = true;
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            result = false;
        }
        return result;
    }

    public static int countImages(String maSanPham) {
        int soLuong = -1;
        try {
            SessionFactory ssFac = HibernateUtil.getSessionFactory();
            Session session = ssFac.getCurrentSession();
            session.beginTransaction();
            String hql = "select count(h.maHinhAnh) from Hinhanh h where h.sanpham.maSanPham=:maSanPham group by h.sanpham.maSanPham";
            Query query = session.createQuery(hql);
            query.setString("maSanPham", maSanPham);
            soLuong = Integer.parseInt(query.uniqueResult().toString());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return soLuong;
    }
}
